package client;

import java.io.IOException;

import javax.swing.JOptionPane;

import shared.Packet;
import shared.Packet0Connect;
import shared.Packet1Chat;
import shared.Packet2Userlist;
import shared.Packet3StyleChat;
import shared.Packet4Peer;
import shared.Packet5InvalidName;

public class PacketHandler {
    TestingClient host;

    public PacketHandler(TestingClient host){
        this.host = host;
    }

    public void handlePacket(Packet packet){
        if(packet.id == 0) handlePacket0Connect((Packet0Connect)packet);
        else if(packet.id == 1) handlePacket1Chat((Packet1Chat)packet);
        else if(packet.id == 2) handlePacket2Userlist((Packet2Userlist)packet);
        else if(packet.id == 3) handlePacket3StyleChat((Packet3StyleChat)packet);
        else if(packet.id == 4) handlePacket4Peer((Packet4Peer)packet);
        else if(packet.id == 5) handlePacket5InvalidName((Packet5InvalidName)packet);
    }

    public void handlePacket0Connect(Packet0Connect packet){
        // Nothing
    }

    public void handlePacket1Chat(Packet1Chat packet){
        host.clientGUI.addLine(packet.message);
    }

    public void handlePacket2Userlist(Packet2Userlist packet){
        host.clientGUI.updateUserList(packet.userlist);
    }
    
    public void handlePacket3StyleChat(Packet3StyleChat packet){
        host.clientGUI.write(packet.from+": ", packet.style);
        host.clientGUI.addLine(packet.message);
    } 
    
    public void handlePacket4Peer(Packet4Peer packet){
    	// TODO - Something
    }
    
    public void handlePacket5InvalidName(Packet5InvalidName packet){
        host.isConnected = false;
        String s = "";
        while(s == "")
            s = (String) JOptionPane.showInputDialog(host.clientGUI,"Please enter a new name:", "Error", JOptionPane.ERROR_MESSAGE, null, null, "Name");
        host.name = s;
        host.packetHandler.sendPacket(new Packet0Connect(host.name));
        host.isConnected = true;
    }

    public void sendPacket(Packet packet){
        try{
            host.out.writeObject(packet);
            host.out.flush();
        }catch(IOException ioException){
            ioException.printStackTrace();
        }
    }
}

